package site.nullable.recorder.ui.components

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Composable
fun WaveformVisualizer(
    amplitude: Int,
    modifier: Modifier = Modifier,
    color: Color? = null
) {
    val maxAmplitude = 32767.0 // MediaRecorder 的最大振幅值
    val normalizedAmplitude = (amplitude / maxAmplitude).coerceIn(0.0, 1.0)

    // 使用主题颜色或默认红色
    val waveformColor = color ?: androidx.compose.material3.MaterialTheme.colorScheme.primary

    Canvas(
        modifier = modifier
            .fillMaxWidth()
            .height(80.dp)
    ) {
        val centerY = size.height / 2
        val barWidth = 4.dp.toPx()
        val spacing = 2.dp.toPx()
        val totalBars = (size.width / (barWidth + spacing)).toInt()

        for (i in 0 until totalBars) {
            val barHeight = (normalizedAmplitude * size.height * 0.8f).toFloat()
            val x = i * (barWidth + spacing)

            drawLine(
                color = waveformColor,
                start = Offset(x, centerY - barHeight / 2),
                end = Offset(x, centerY + barHeight / 2),
                strokeWidth = barWidth
            )
        }
    }
}